package com.kb.erp.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kb.erp.config.CellWriteHeightConfig;
import com.kb.erp.config.CellWriteWidthConfig;
import com.kb.erp.domain.DetailSearchVO;
import com.kb.erp.entity.FlowChartQueue;
import com.kb.erp.entity.flow.FlowDataSyn;
import com.kb.erp.entity.flow.FlowJsonData;
import com.kb.erp.entity.flow.SpecialOrderProcessExcel;
import com.kb.erp.mapper.sqlServer.CommonMapper;
import com.kb.erp.mapper.sqlServer.flow.FlowDataSynMapper;
import com.kb.erp.mapper.sqlServer.flow.FlowJsonDataMapper;
import com.kb.erp.mapper.sqlServer.flow.FlowchartMapper;
import com.kb.erp.service.DYYService;
import com.kb.erp.service.FlowChartQueueService;
import com.kb.erp.util.StyleUtils;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@DS("FlowChart")
@Service
@Slf4j
public class FlowChartQueueServiceImpl extends ServiceImpl<CommonMapper, FlowChartQueue> implements FlowChartQueueService {

    @Resource
    private CommonMapper commonMapper;
    @Resource
    private FlowchartMapper flowchartMapper;
    @Resource
    private FlowJsonDataMapper flowJsonDataMapper;
    @Resource
    private FlowDataSynMapper flowDataSynMapper;
    @Resource
    private DYYService dyyService;

    @Override
    public void updateStatus() {
        LambdaQueryWrapper<FlowChartQueue> queryWrapper = Wrappers.lambdaQuery();


        // 获取当前时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 获取两天前的日期
        LocalDateTime twoDaysAgo = currentDateTime.minusDays(2);
        // 将日期格式化为字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedTwoDaysAgo = twoDaysAgo.format(formatter);


        queryWrapper.eq(FlowChartQueue::getFStatus, 2).like(FlowChartQueue::getFData, "\"formTitle\":\"电子领料_").gt(FlowChartQueue::getFCreateDate, formattedTwoDaysAgo);
        List<FlowChartQueue> flowChartQueues = commonMapper.selectList(queryWrapper);
        XxlJobHelper.log("查询到可更新数量：" + flowChartQueues.size());

        if (CollectionUtils.isNotEmpty(flowChartQueues)) {
            for (FlowChartQueue chartQueue : flowChartQueues) {
                LambdaQueryWrapper<FlowChartQueue> update = Wrappers.lambdaQuery();
                update.eq(FlowChartQueue::getFID, chartQueue.getFID());
                chartQueue.setFStatus(0);
                System.out.println(chartQueue.getFID());
                XxlJobHelper.log("更新状态的id：" + chartQueue.getFID());
                this.update(chartQueue, update);

            }
        }

    }

    @Override
    public void flowDataSyn() {
        try {
            //查找需要同步的流程
            List<FlowDataSyn> flowchartList = flowDataSynMapper.queryList();
            //解析数据
            String dyyToken = dyyService.getDYYToken();
            ObjectMapper objectMapper = new ObjectMapper();
            //ormStopTime	最后处理时间	开始时间_结束时间
            // 获取当前时间
            LocalDateTime currentDateTime = LocalDateTime.now();
            // 获取两天前的日期
            LocalDateTime twoDaysAgo = currentDateTime.minusDays(2);
            // 将日期格式化为字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedTwoDaysAgo = twoDaysAgo.format(formatter);
            String formattedNow = currentDateTime.format(formatter);
            String time = formattedTwoDaysAgo + "_" + formattedNow;



            for (FlowDataSyn flowchart : flowchartList) {
                //获取表单数据
                String flowId = flowchart.getFlowId();
                String formOrder = "https://qwif.do1.com.cn/qwcgi/api/apiFormExport/getFormOrder.do?token=" + dyyToken + "&corpId=wx4f594cea21b39022&id=" + flowchart.getFlowId() ;
                Map map = new HashMap();
                HashMap<String, Object> formParamMap = new HashMap<>();
                map.put("id",flowId);
                map.put("pageNO",1);
                map.put("pageSize",1);
                formParamMap.put("data",JSONUtil.parse(map).toString());
                String formPost = HttpUtil.post(formOrder, formParamMap);
                JsonNode formPageData = objectMapper.readTree(formPost).get("data").get("pageData");
                List<Map<String, Object>> formProcessCenterMap = objectMapper.readValue(formPageData.traverse(), new TypeReference<List<Map<String, Object>>>() {
                });
                //
                HashMap<String, String> formMap = new HashMap<>();
                for (Map<String, Object> stringObjectMap : formProcessCenterMap) {
                    String formName = stringObjectMap.get("formName").toString();
                    String typeName = stringObjectMap.get("typeName").toString();
                    formMap.put("formName", formName);
                    formMap.put("typeName", typeName);
                }
                //  //先获取总数据量
                int pageSize = 1000;
                String url = "https://qwif.do1.com.cn/qwcgi/api/apiForm/getFormDetails.do?token=" + dyyToken + "&corpId=wx4f594cea21b39022&id=" + flowchart.getFlowId() + "&pageSize=" + pageSize;
                log.info(flowchart.getFlowId()+"------");

                //查询 -1:关闭;0:退审;1:全部审核通过;2:流转中，多个用英文竖线"|"隔开
                //todo 查询条件 {     "isOver": "-1|0|1|2",     "formStopTime":"2024-09-30 11:48:20_2024-10-01 10:59:29" }
                HashMap<String, Object> paramMap = new HashMap<>();
                DetailSearchVO detailSearchVO = new DetailSearchVO();
                detailSearchVO.setIsOver("1|0|1|2");
                detailSearchVO.setFormStopTime(time);

                String pagePostInfo = HttpUtil.post(url, paramMap);
                //每次为1000条时，最大的分页数量
                int maxPage = objectMapper.readTree(pagePostInfo).get("data").get("maxPage").asInt();
                for (int i = 1; i <= maxPage; i++) {

                    String pageUrl = "https://qwif.do1.com.cn/qwcgi/api/apiForm/getFormDetails.do?token=" + dyyToken + "&corpId=wx4f594cea21b39022&id=" + flowchart.getFlowId() +"&page="+i+ "&pageSize=" + pageSize;
                    //只有type为0的流程才需要加条件查询数据
                    if (!Objects.equals(flowchart.getType(), 1)) {
                        String parse = JSONUtil.parse(detailSearchVO).toString();
                        paramMap.put("detailSearchVO", parse);
                    }

                    String pagePost = HttpUtil.post(pageUrl, paramMap);
                    JsonNode PageData = objectMapper.readTree(pagePost).get("data").get("pager");
                    if (Objects.isNull(PageData)) {
                        break;
                    }
                    List<Map<String, Object>> processCenterMap = objectMapper.readValue(PageData.traverse(), new TypeReference<List<Map<String, Object>>>() {
                    });
                    log.info("{}: 数量", processCenterMap.size());
                    XxlJobHelper.log("数量：" + processCenterMap.size());

//                List<FlowJsonData> list = new ArrayList<>();
                    for (Map<String, Object> objectMap : processCenterMap) {
                        FlowJsonData flowJsonData = new FlowJsonData();
                        String workId = objectMap.get("id").toString();
                        flowJsonData.setStatus((String) objectMap.get("auditStatusStr"));
                        flowJsonData.setCloseTime(DateUtil.parseLocalDateTime((String) objectMap.get("closeTime"), "yyyy-MM-dd HH:mm:ss"));
                        flowJsonData.setCreateTime(DateUtil.parseLocalDateTime((String) objectMap.get("createaTime"), "yyyy-MM-dd HH:mm:ss"));
                        flowJsonData.setPersonName((String) objectMap.get("personName"));
                        flowJsonData.setFormTitle((String) objectMap.get("formTitle"));
                        flowJsonData.setVersions((Integer) objectMap.get("versions"));
                        flowJsonData.setDepartmentName((String) objectMap.get("departmentName"));
                        flowJsonData.setClosePersonName((String) objectMap.get("closePersonName"));
                        //通过接口获取
                        flowJsonData.setFormName(formMap.get("formName"));
                        flowJsonData.setTypeName(formMap.get("typeName"));
                        flowJsonData.setWorkId(workId);
                        String jsonString = objectMapper.writeValueAsString(objectMap);
                        flowJsonData.setText(jsonString);
                        flowJsonData.setFormId(flowchart.getFlowId());

                        //查询数据是否存在，不存在insert,存在状态为流转中或者状态不相等删除再插入1
                        if (!Objects.equals(flowchart.getType(), 1)) {
                            FlowJsonData jsonDataList = flowJsonDataMapper.queryDataByStatus(workId);
                            if (Objects.isNull(jsonDataList)) {
                                flowJsonDataMapper.insert(flowJsonData);
                                XxlJobHelper.log("新增数据：" + workId);
                                log.info("新增数据：{}", workId);
                            } else if (!Objects.equals(jsonDataList.getCloseTime(), flowJsonData.getCloseTime())) {
                                flowJsonDataMapper.delByWorkId(workId);
                                flowJsonDataMapper.insert(flowJsonData);
                                log.info("更新数据：{}", workId);
                                XxlJobHelper.log("更新数据：" + workId);
                            }
                        } else {
                            //流程第一次初始化数据
                            flowJsonDataMapper.insert(flowJsonData);
                            XxlJobHelper.log("初始化成功");
                            //修改type为0
//                        flowJsonDataMapper.updateType
                        }

                    }
                }

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //入库

    }

    @Override
    public void specialOrderProcess(FlowJsonData flowJsonData, HttpServletResponse response) {
        String formId = flowJsonData.getFormId();
        log.info("开始处理数据：{}", formId);
        //获取总共有多少条数据 逻辑：获取到数据条数，再根据模板，组装自己要的数据
        try {
            //待评审物料种类key
            String key1 = "foe93d7823df1540f4b9c4d8a22a30ec5d";
            String key2 = "fodbb1bc649f8e4e21b4162f575b998d5e"; //客户代码
            String key3 = "fo9baed4477e684cdc9c2d4d95f53114ad"; //油墨数组
            String key4 = "fod55add6d23e6437e8208974c740b12f7"; //板材数组
            String key5 = "fod0416fbfbd074d08be9653bbb03aed58"; //半固化片数组

            //油墨
            String yKey1 = "foc637c8bcad00489685c7e7973a5dfa86"; //产品型号
            String yKey2 = "fof19ea402751142478ba48b5effa61670"; //颜色
            String yKey3 = "fod4fa6168cc024942863ae38536f0bbb0"; //规格/包装
            String yKey4 = "fodce69f18b7a04c37ae26386fbcb0a7b7"; //MOQ（最小起订量）
            String yKey5 = "fo1180f4ab773747c98b0bf97c8f1bb7c6"; //单价
            String yKey6 = "fobff5f2908083475aab41fdd9dd90fbc4"; //备注
            String yKey7 = "fo11b0c46f953949c9925e57d34617ca8a"; //交期
            String yKey8 = "fo120cc84cb67e41439be0bb55cddfbb3c"; //材料供应商

            //板材
            String bkey1 = "fod6d828dc9f614815beca2a572dc1d29a";//名称
            String bkey2 = "fode2c98e5150246baa4003908b4d3ca14";//MQQ
            String bkey3 = "fo94041cacb2374df986e236099138b1a2";//板材类型
            String bkey4 = "fo9365a438473d42fcbd71122d691c6953";//尺寸
            String bkey5 = "foc96d4ce81f454ceda0fdfeb0a87712d9";//单价
            String bkey6 = "fo5230ff8e39894d8faef51c62c050763a";//交期
            String bkey7 = "fo8b339555b1b24bf29592e0e5470b3422";//备注
            String bkey11 = "fo004d3c83ee1e46fb869a97b124764ef5";//咨询数

            String bkey8 = "fo26ebfe0a0a02422d83ddfe803daa86b7";//厚度
            String bkey9 = "foda5b2d861db44e83955a390cd19e8ea2";//铜箔
            String bkey10 = "fo9365a438473d42fcbd71122d691c6953";//尺寸

            //半固化片数组
            String gkey1 = "foc8b4b807a6de476cab8f85fce8baae90";//型号
            String gkey2 = "fod80ccca3ea154e9f9db972e48652e91e";//厚度尺寸
            String gkey3 = "fo8233712666224e7c97c10290853e573a";//厂商
            String gkey4 = "fo1d974e12a16a40c0869080fbbcea67e0";//布种
            String gkey5 = "fo3f645e672a924611a6d7a647f5d44324";//RC范围
            String gkey6 = "fodf55cc49d12c4ea8a52f2e725b2c94dc";//MOQ
            String gkey7 = "fo7e202e320f5643559940a4afa889d0f1";//单价
            String gkey8 = "foc6123832b1c2468db6d6eaf93ab8c6b2";//交期
            String gkey9 = "";//备注


            List<SpecialOrderProcessExcel> list = new ArrayList<>();
            LambdaQueryWrapper<FlowJsonData> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(FlowJsonData::getFormId, formId);
            if (Objects.nonNull(flowJsonData.getStatus()) && !flowJsonData.getStatus().isEmpty())
                queryWrapper.eq(FlowJsonData::getStatus, flowJsonData.getStatus());

            if (Objects.nonNull(flowJsonData.getPersonName()))
                queryWrapper.eq(FlowJsonData::getPersonName, flowJsonData.getPersonName());
            if (Objects.nonNull(flowJsonData.getCreateTimeStr()))
                queryWrapper.ge(FlowJsonData::getCreateTime, flowJsonData.getCreateTimeStr());
            if (Objects.nonNull(flowJsonData.getCloseTimeStr()))
                queryWrapper.le(FlowJsonData::getCloseTime, flowJsonData.getCloseTimeStr());
            queryWrapper.orderByDesc(FlowJsonData::getCloseTime);

            List<FlowJsonData> flowcharts = flowJsonDataMapper.selectList(queryWrapper);
            log.info("查询数据量：{}", flowcharts.size());
            ObjectMapper objectMapper = new ObjectMapper();
            for (FlowJsonData flowchart : flowcharts) {
//            解析数据
                JsonNode jsonNode = objectMapper.readTree(flowchart.getText());
                String createTime = jsonNode.get("createaTime").asText();
                String personName = jsonNode.get("personName").asText();
                JsonNode data = jsonNode.get("data");
                JsonNode arrayNode = data.get(key1);
                JsonNode custCode = data.get(key2);


                if (arrayNode != null && arrayNode.isArray()) {
                    for (JsonNode item : arrayNode) {
                        if (item.asText().equals("板材")) {
                            JsonNode bcList = data.get(key4);
                            if (bcList != null && bcList.isArray()) {
                                for (JsonNode node : bcList) {
                                    SpecialOrderProcessExcel specialOrderProcessExcel = new SpecialOrderProcessExcel();
                                    specialOrderProcessExcel.setType(item.asText());
                                    specialOrderProcessExcel.setCreateTime(createTime);
                                    specialOrderProcessExcel.setPersonName(personName);
                                    if (Objects.nonNull(custCode)) {
                                        specialOrderProcessExcel.setCustCode(custCode.asText());
                                    }
                                    specialOrderProcessExcel.setMaterialName(node.get(bkey1).asText());
                                    //单价
                                    String bkey5Value = "";
                                    if (Objects.nonNull(node.get(bkey5))) {
                                        bkey5Value = node.get(bkey5).asText();
                                    }

                                    if (Objects.nonNull(node.get(bkey5)))
                                        specialOrderProcessExcel.setUnitPrice(bkey5Value);
                                    if (Objects.nonNull(node.get(bkey2)))
                                        specialOrderProcessExcel.setMOQ(node.get(bkey2).asText());
                                    if (Objects.nonNull(node.get(bkey7)))
                                        specialOrderProcessExcel.setRemark(node.get(bkey7).asText());
                                    if (Objects.nonNull(node.get(bkey6)))
                                        specialOrderProcessExcel.setPeriod(node.get(bkey6).asText());
                                    //型号
                                    String key8 = node.get(bkey8).asText(); //厚度
                                    String key9 = "";
                                    if (Objects.nonNull(node.get(bkey9))) {
                                        key9 = node.get(bkey9).asText();
                                    }
                                    String bckey3 = "";
                                    if (Objects.nonNull(node.get(bkey3))) {
                                        bckey3 = node.get(bkey3).asText();
                                    }
                                    //尺寸
                                    String bkey4Value = "";
                                    if (Objects.nonNull(node.get(bkey4))) {
                                        bkey4Value = node.get(bkey4).asText();
                                    }
                                    //铜箔
                                    String bkey9Value = "";
                                    if (Objects.nonNull(node.get(bkey9))) {
                                        bkey9Value = node.get(bkey4).asText();
                                    }
                                    //咨询数
                                    String bkey11Value = "";
                                    if (Objects.nonNull(node.get(bkey11))) {
                                        bkey11Value = node.get(bkey11).asText();
                                    }
                                    String key10 = node.get(bkey10).asText();
                                    specialOrderProcessExcel.setSpecificationModel(node.get(bkey1).asText() + " " + key8 + " " + key9 + " " + bckey3 + " " +bkey9Value +" "+ key10 + " " + bkey11Value);

                                    list.add(specialOrderProcessExcel);
                                }
                            }
                        } else if (item.asText().equals("油墨")) {
                            JsonNode ymList = data.get(key3);
                            if (ymList != null && ymList.isArray()) {
                                for (JsonNode node : ymList) {
                                    SpecialOrderProcessExcel specialOrderProcessExcel = new SpecialOrderProcessExcel();
                                    specialOrderProcessExcel.setType(item.asText());
                                    specialOrderProcessExcel.setCreateTime(createTime);
                                    specialOrderProcessExcel.setPersonName(personName);
                                    if (Objects.nonNull(custCode)) {
                                        specialOrderProcessExcel.setCustCode(custCode.asText());
                                    }
                                    //物料名称
                                    specialOrderProcessExcel.setMaterialName(node.get(yKey1).asText());
                                    //单价
                                    if (Objects.nonNull(node.get(yKey5)))
                                        specialOrderProcessExcel.setUnitPrice(node.get(yKey5).asText());
                                    //MOQ
                                    if (Objects.nonNull(node.get(yKey4)))
                                        specialOrderProcessExcel.setMOQ(node.get(yKey4).asText());
                                    //备注
                                    if (Objects.nonNull(node.get(yKey6)))
                                        specialOrderProcessExcel.setRemark(node.get(yKey6).asText());
                                    //采购周期
                                    if (Objects.nonNull(node.get(yKey7)))
                                        specialOrderProcessExcel.setPeriod(node.get(yKey7).asText());

                                    //型号， 由多个字段拼接
                                    String Key1 = node.get(yKey1).asText();
                                    //颜色
                                    Object Key2 = "";
                                    if (Objects.nonNull(node.get(yKey2))) {
                                        Key2 = node.get(yKey2);
                                    }
                                    //规格包装
                                    String key10 = node.get(yKey3).asText();
                                    //材料供应商
                                    Object yKey8Value = node.get(yKey8);

                                    specialOrderProcessExcel.setSpecificationModel(Key1 + " " + Key2 + " " + key10 + " " + yKey8Value);

                                    list.add(specialOrderProcessExcel);
                                }

                            }
                        } else {
                            //半固化片数组
                            JsonNode otherList = data.get(key5);
                            if (otherList != null && otherList.isArray()) {
                                for (JsonNode node : otherList) {
                                    SpecialOrderProcessExcel specialOrderProcessExcel = new SpecialOrderProcessExcel();
                                    specialOrderProcessExcel.setType(item.asText());
                                    specialOrderProcessExcel.setCreateTime(createTime);
                                    specialOrderProcessExcel.setPersonName(personName);
                                    if (Objects.nonNull(custCode)) {
                                        specialOrderProcessExcel.setCustCode(custCode.asText());
                                    }
                                    //物料名称
                                    specialOrderProcessExcel.setMaterialName(node.get(gkey1).asText());
                                    //单价
                                    if (Objects.nonNull(node.get(gkey7)))
                                        specialOrderProcessExcel.setUnitPrice(node.get(gkey7).asText());
                                    //MOQ
                                    if (Objects.nonNull(node.get(gkey6)))
                                        specialOrderProcessExcel.setMOQ(node.get(gkey6).asText());
                                    //备注
//                                if (Objects.nonNull(node.get(yKey6)))specialOrderProcessExcel.setRemark(node.get(yKey6).asText());
                                    //采购周期
                                    if (Objects.nonNull(node.get(gkey8)))
                                        specialOrderProcessExcel.setPeriod(node.get(gkey8).asText());

                                    //型号， 由多个字段拼接
                                    String Key1 = node.get(gkey1).asText();
                                    String Key2 = "";//厚度
                                    if (Objects.nonNull(node.get(gkey2))) {
                                        Key2 = node.get(gkey2).asText();
                                    }
                                    String pkey3 = "";//布种
                                    if (Objects.nonNull(node.get(gkey4))) {
                                        pkey3 = node.get(gkey4).asText();
                                    }
                                    String pkey5Value = ""; //RC范围
                                    if (Objects.nonNull(node.get(gkey5))) {
                                        pkey5Value = node.get(gkey5).asText();
                                    }
                                    specialOrderProcessExcel.setSpecificationModel(Key1 + " " + Key2 + " " + pkey3 + " " + pkey5Value+"%");

                                    list.add(specialOrderProcessExcel);
                                }
                            }
                        }

                    }
                }

            }

            // 加载模板文件
            // 设置下载文件名
            // 生成文件名
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String currentDate = sdf.format(new Date());
            String fileName = "特殊订单物料评审信息汇总" + currentDate + ".xlsx";
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);

            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(StyleUtils.getHeadStyle(), StyleUtils.getContentStyle());

            // 使用 EasyExcel 直接写入到响应的输出流
            try (
                    ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), SpecialOrderProcessExcel.class)
                            .registerWriteHandler(new CellWriteWidthConfig()) // 自适应列宽
                            .registerWriteHandler(new CellWriteHeightConfig()) // 自适应行高
                            .registerWriteHandler(horizontalCellStyleStrategy)
                            .build()) {
                excelWriter.write(list, EasyExcel.writerSheet("特殊订单").build());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


}
